<!--分为全部解析和错题解析-->


<script setup>
import CommonQuestion from "@/components/common/CommonQuestion.vue";
import UseTemp from '@/stores/temp.js'
import {useRoute, useRouter} from "vue-router";
import PaperApis from "@/apis/paper.js";
import QuestionApis from "@/apis/question.js";
import NoteApis from "@/apis/note.js";
import {ElMessage} from "element-plus";
import {computed} from "vue";


const showLeft = ref(true)
const loading = ref(false)
const route = useRoute()
const tempStore = UseTemp();
const response = ref(null)
const questionData = ref(null)

const router = useRouter()
// const userStore = useUserStore()
const qCount = ref(0)
const common = ref(null)


const currentIndex = ref(null)
const firstTypeMap = {
  1: 'singleChoice',
  2: 'multipleChoice',
  3: 'judgement',
  4: 'fill',
  5: 'text',
  6: 'combination',
  7: 'indefiniteMultipleChoice'
}
const currentQuestion = computed(() => {
  if (currentIndex.value) {
    return questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];
  }
})
const currentOptionsStatus = computed(() => {
  if (currentIndex.value != undefined) {
    // console.log(questionData.value.content,currentIndex.value)
    let currentCard = questionData.value.content[currentIndex.value[0]].qs[currentIndex.value[1]];

    if (currentCard.answerStatus == 'done') {
      // 多选为数组
      let answer;
      try {
        answer = JSON.parse(currentCard.record.as);
      } catch (err) {
        answer = currentCard.record.as
      }

      // 多选为数组
      let rightAnswer = currentCard.rightAnswer;

      // 判断题选项0、1
      switch (currentCard.firstType) {
        case 1:
        case 3:
          if (answer == rightAnswer) {
            return {
              right: answer,
              wrong: ''
            }
          } else {
            return {
              right: rightAnswer,
              wrong: answer
            }
          }
          break;
          // 多选、不定项
        case 2:
        case 7:
          answer.sort((a, b) => {
            return a.charCodeAt(0) - b.charCodeAt(0)
          });
          answer = answer.toString();
          if (answer == rightAnswer.toString()) {
            return {
              right: rightAnswer,
              wrong: [],
              noSelected: []
            }
          } else {
            let arr1 = answer.split(',')
            let arr2 = [...rightAnswer]
            let right = []
            let wrong = []
            let noSelected = []
            for (let i = 0; i < arr1.length; i++) {
              let findIndex = arr2.findIndex((e) => {
                return e == arr1[i]
              })
              // 正确且选中
              if (findIndex > -1) {
                right.push(arr1[i])
                arr2.splice(findIndex, 1)
              } else {
                wrong.push(arr1[i])
              }
            }
            noSelected.push(...arr2)
            return {
              right,
              wrong,
              noSelected
            }
          }
          break;
        case 4:
          return {}
          break;
        default:
          break;
      }
    }
    return {}
  }
})

//根据路由传入的paperId
function init() {
  if (tempStore.examResult) {
    response.value = tempStore.examResult
    if (response.value.paperRecords.id == route.query.id) {

      currentIndex.value = [0, 0]
      let num = 0;
      if (route.query.type == 'all') {

        questionData.value =response.value.collectStructure
        response.value.collectStructure.content.forEach(e => {
          e.qs.forEach(el => {
            num ++
            el.num=num;
            if (el.record) {
              el.answerStatus = 'done'
              initAnswer(el,el.record.as,el.firstType)
            } else {
              el.answerStatus = 'notDone'
              initAnswer(el,null,el.firstType)
            }
          })
        })
        qCount.value = response.value.paperRecords.qcount;
      } else if(route.query.type=='error'){

        qCount.value = response.value.paperRecords.errorCount;
        // 空的大题型要去掉,只保留错题
        for(let i=0;i<response.value.collectStructure.content.length;i++){
          let a=0;
          for(let j=0;j<response.value.collectStructure.content[i].qs.length;j++){

            if(response.value.collectStructure.content[i].qs[j].record&&!response.value.collectStructure.content[i].qs[j].record.rt){

              num++
              response.value.collectStructure.content[i].qs[j].num=num
              response.value.collectStructure.content[i].qs[j].answerStatus = 'done'
              initAnswer(response.value.collectStructure.content[i].qs[j],response.value.collectStructure.content[i].qs[j].record.as,response.value.collectStructure.content[i].qs[j].firstType)
            }else{
              response.value.collectStructure.content[i].qs.splice(j,1)
              j--;
            }

          }
          if(response.value.collectStructure.content[i].qs.length==0){
            response.value.collectStructure.content.splice(i,1)
            i--;
          }
        }
        questionData.value = response.value.collectStructure
      }

      return
    }

  }
  loading.value = true
//   请求
  PaperApis.paperResult({
    params: {
      recordsId: route.query.id,
      industryCode: route.query.industryCode,
      examId: route.query.examId,
      categoryId: route.query.categoryId,
      structure: false
    }
  }).then(res => {
    loading.value = false
    response.value = res.data



    let num = 0;
    if (route.query.type == 'all') {
      questionData.value = res.data.collectStructure
      res.data.collectStructure.content.forEach(e => {

        e.qs.forEach(el => {
          num ++
          el.num=num;
          if (el.record) {
            el.answerStatus = 'done'
            initAnswer(el,el.record.as,el.firstType)
          } else {
            el.answerStatus = 'notDone'
            initAnswer(el,null,el.firstType)
          }
        })
      })
      qCount.value = res.data.paperRecords.qcount;
    }else if(route.query.type=='error'){

      qCount.value = res.data.paperRecords.errorCount;
      // 空的大题型要去掉,只保留错题
      for(let i=0;i<res.data.collectStructure.content.length;i++){
        let a=0;
        for(let j=0;j<res.data.collectStructure.content[i].qs.length;j++){

          if(res.data.collectStructure.content[i].qs[j].record&&!res.data.collectStructure.content[i].qs[j].record.rt){

            num++
            res.data.collectStructure.content[i].qs[j].num=num
            res.data.collectStructure.content[i].qs[j].answerStatus = 'done'
            initAnswer(res.data.collectStructure.content[i].qs[j],res.data.collectStructure.content[i].qs[j].record.as,res.data.collectStructure.content[i].qs[j].firstType)
          }else{
            res.data.collectStructure.content[i].qs.splice(j,1)
            j--;
          }

        }
        if(res.data.collectStructure.content[i].qs.length==0){
          res.data.collectStructure.content.splice(i,1)
          i--;
        }
      }
      questionData.value = res.data.collectStructure
    }
    currentIndex.value = [0, 0]

  })
}

function initAnswer(targetObj,right,firstType){
  if(right){
    if (firstType == 4) {
      let array = right.split(' ')
      for (let i = 0; i < array.length; i++) {
        targetObj['answer' + i] = array[i]
      }
      targetObj.answer = e.record.as
    }else{
      try{
        targetObj.answer=JSON.parse(right)
      }catch (err) {
        targetObj.answer=right
      }
    }
  }else{
    if (firstType == 4) {
      let array = right.split(' ')
      for (let i = 0; i < targetObj.quOption.length; i++) {
        targetObj['answer' + i] = null
      }
      targetObj.answer = null
    }else{
      targetObj.answer = [1, 3, 5].includes(firstType) ? '' : [];
      targetObj.lockAnswer = [1, 3, 5].includes(firstType) ? '' : [];
    }
  }

}
function toggleNote() {
  if (!currentQuestion.value.collect) {
    QuestionApis.collectQuestion({
      industryCode: route.query.industryCode,
      examId: route.query.examId,
      categoryId: route.query.categoryId,
      // industryName: userStore.selectCategory.industryName,
      // examName: userStore.selectCategory.examName,
      // categoryName: userStore.selectCategory.categoryName,
      columnId: route.query.columnId,
      qid: currentQuestion.value.id,
      true: true,
      recordsType: 'everyday',
      data: {
        qt: currentQuestion.value.firstType,
        // qt: firstTypeMap1[currentQuestion.value.firstType],
        tr: '',
        // 章节id为试卷id吗
        cid: route.query.id,
        ct: 'everyday',
        cn: questionData.value.name,
        as: currentQuestion.value.answer,
        sn: currentQuestion.value.sign,
        t: new Date().getTime(),
        st: currentQuestion.value.stem

      }
    }).then(res => {
      if (res.data == true) {
        currentQuestion.value.collect = true
        currentQuestion.value.notedTime = new Date().getTime()
      }
      // QuestionApis.paperRecordsCollect(localStore.userSelectedIdsMap)
    })
  } else {
    QuestionApis.delCollect({
      industryCode: route.query.industryCode,
      examId: route.query.examId,
      categoryId: route.query.categoryId,
      // industryName: userStore.selectCategory.industryName,
      // examName: userStore.selectCategory.examName,
      // categoryName: userStore.selectCategory.categoryName,
      columnId: route.query.columnId,
      qid: currentQuestion.value.id,
    }).then(res => {
      if (res.success == true) {
        currentQuestion.value.collect = false
        currentQuestion.value.notedTime = 0
      }
    })
  }
}

function toggle() {
  showLeft.value = !showLeft.value
}

function saveNote(formData) {
  if (common.value.noteAction == 'save') {
    NoteApis.publishNote({
      ...formData,
      type: 'paper',
      // 关联id就是章节id之类的
      relationId: route.query.id,
      // verify:'',
      questionId: currentQuestion.value.id,
      categoryId: route.query.categoryId,
    }).then(res => {
      common.value.setDraw(false)
      ElMessage({
        message: '笔记保存成功',
        type: 'success'
      })
    }).catch(_ => {
      ElMessage({
        message: '笔记保存失败',
        type: 'error'
      })
    })
  } else {
    NoteApis.updateNote({
      ...formData,
    }).then(res => {
      common.value.setDraw(false)
      ElMessage({
        message: '笔记更新成功',
        type: 'success'
      })
    }).catch(_ => {
      ElMessage({
        message: '笔记更新失败',
        type: 'error'
      })
    })
  }
}

function doNote() {
//   用el-drawer
  common.value.setDraw(true)
//   获取笔记详情
  NoteApis.getNoteList({
    params: {
      type: 'paper',
      relationId: route.query.id,
      questionId: currentQuestion.value.id,
      categoryId: route.query.categoryId,
    }
  }).then(res => {
    if (res.data.length > 0) {
      common.value.noteAction = 'edit'
      common.value.setFormData(res.data[0])
    } else {
      common.value.noteAction = 'save'
    }
  })
}

function changeCurrent(i, j) {
  const [index1, index2] = currentIndex.value
  questionData.value.content[index1].qs[index2].current = false
  questionData.value.content[i].qs[j].current = true
  currentIndex.value = [i, j]
}

function nextQuestion() {
  let current = currentQuestion.value.num
  if (current >= qCount.value) {
    return
  }
  currentQuestion.value.current = false;
  let aa = 0
  a:for (let i of questionData.value.content) {
    let b = 0;
    for (let j of i.qs) {
      if (j.num == current + 1) {
        currentIndex.value = [aa, b]
        j.current = true;
        break a;
      }
      b++
    }
    aa++
  }
}

function preQuestion() {
  let current = currentQuestion.value.num
  if (current <= 1) {
    return
  }
  currentQuestion.value.current = false;
  let aa = 0
  a:for (let i of questionData.value.content) {
    let b = 0;
    for (let j of i.qs) {
      if (j.num == current - 1) {
        currentIndex.value = [aa, b]
        j.current = true;
        break a;
      }
      b++
    }
    aa++
  }
}

init()


</script>

<template>
  <div>
    <CommonQuestion ref="common" :change-checkbox="()=>{}" :change-current="changeCurrent" :change-radio="()=>{}"
                    :current-options-status="currentOptionsStatus"
                    :current-question="currentQuestion"
                    :do-note="doNote" :loading="loading" :next-question="nextQuestion" :pre-question="preQuestion"
                    :q-count="qCount" :question-data="questionData" :save-and-exit="()=>{}"
                    :save-note="saveNote" :show-left="showLeft" :submit-this="()=>{}" :toggle="toggle"
                    :toggle-note="toggleNote" disabled/>
  </div>
</template>

<style scoped>

</style>